//
//  XOClubPublishController.m
//  didigo
//
//  Created by JS_Coder on 2019/2/18.
//  Copyright © 2019 lifayu. All rights reserved.
//

#import "XOClubPublishController.h"
#import "XOClubPublishImageCell.h"
#import "EJSClubPublishRequest.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <SVProgressHUD.h>
@interface XOClubPublishController ()<UITextViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, XOClubPublishProtocol> {
    Boolean _isLoading;
}

@end

@implementation XOClubPublishController

#pragma UITextView
- (UITextView *)textView {
    if (_textView != nil){
        return _textView;
    }
    CGRect frame = CGRectMake(15, 15, ScreenWidth - 30, 250);
    _textView = [[UITextView alloc]initWithFrame:frame];
    _textView.text = @"请输入内容";
    _textView.font = CHINESE_PingFangRegular(15);
    _textView.textColor = UIColor.lightGrayColor;
    _textView.delegate = self;
    _textView.layer.cornerRadius = 8;
    _textView.layer.masksToBounds = YES;
    return _textView;
}

#pragma CollectionView
- (UICollectionView *)collectionView {
    if (_collectionView != nil) {
        return _collectionView;
    }
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.itemSize = CGSizeMake(110, 110);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    CGRect frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame) + 15, ScreenWidth, 110);
    _collectionView = [[UICollectionView alloc]initWithFrame:frame collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = UIColor.whiteColor;
    _collectionView.layer.cornerRadius = 8;
    _collectionView.layer.masksToBounds = YES;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"XOClubPublishImageCell" bundle:nil] forCellWithReuseIdentifier:@"XOClubPublishImageCell"];
    return _collectionView;
}

- (NSMutableArray *)imageArr {
    if (_imageArr != nil) {
        return _imageArr;
    }
    _imageArr = [[NSMutableArray alloc]init];
    [_imageArr addObject:[UIImage imageNamed:@"publishPlaceholder"]];
    return _imageArr;
}

#pragma PublishButton
- (UIButton *)publishButton {
    if (_publishButton != nil) {
        return _publishButton;
    }
    CGRect frame = CGRectMake(15, CGRectGetMaxY(self.collectionView.frame) + 30, ScreenWidth - 30, 55);
    _publishButton = [[UIButton alloc]initWithFrame:frame];
    [_publishButton setTitle:@"发布" forState:UIControlStateNormal];
    [_publishButton setTitleColor:AppTextColor forState:UIControlStateHighlighted];
    [_publishButton setBackgroundColor:AppMainColor];
    _publishButton.layer.cornerRadius = 55 * 0.5;
    _publishButton.layer.shadowRadius = 5;
    _publishButton.layer.shadowOffset =  CGSizeMake(0, 2);           //阴影的偏移量
    _publishButton.layer.shadowOpacity = 0.8;                        //阴影的不透明度
    _publishButton.layer.shadowColor = AppMainColor.CGColor;
    [_publishButton addTarget:self action:@selector(publishButtonAction) forControlEvents:UIControlEventTouchUpInside];
    return _publishButton;
}

#pragma Life
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)configOwnViews {
    self.title = @"发布";
    self.view.backgroundColor = UIColorFromRGB(0xF5F5F5);
    [self configNavigationLeftItemWithImage:[UIImage imageNamed:@"back_icon"]];
    [self.view addSubview:self.textView];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.publishButton];
}


#pragma 发布点击
- (void)publishButtonAction {
    if (_isLoading) {
        return;
    }
    if (![EJSUserModel userModel]) {
        [[HUDHelper sharedInstance] tipMessage:@"请先登录后,再发布"];
        return;
    }
    _isLoading = YES;
    if (self.imageArr.count > 1 || (self.textView.text.length > 0 && ![self.textView.text isEqualToString:@"请输入内容"]) ) {
        [SVProgressHUD show];
        EJSCLubPublishRequest *request = [EJSCLubPublishRequest new];
        request.content = [self.textView.text isEqualToString:@"请输入内容"] ?@"" :self.textView.text;
        request.pic = @"pic";
        NSMutableArray *tempImgs = [[NSMutableArray alloc]initWithArray:self.imageArr];
        [tempImgs removeObjectAtIndex:0];
        NSMutableArray *requestImages = [[NSMutableArray alloc]init];
        for (UIImage *img in tempImgs) {
            [requestImages addObject: [self resetSizeOfImageData:img maxSize:100]];
        }

        FlyWeakSelf
        [request uploadMultiImages:requestImages uploadName:@"pic" progress:nil successHandler:^(BaseResponse *response) {
            _isLoading = NO;
            [SVProgressHUD dismiss];
            [[HUDHelper sharedInstance]tipMessage:@"发布成功"];
            [weakSelf canUpdateClub];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        } failHandler:^(BaseResponse *response) {
            _isLoading = NO;
            [SVProgressHUD dismiss];
            [[HUDHelper sharedInstance]tipMessage:@"上传失败"];
        }];
    }else {
        _isLoading = NO;
        [[HUDHelper sharedInstance]tipMessage:@"请输入内容或者放入图片"];
    }
}


- (void)canUpdateClub {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"canUpdateClub" object:nil];
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    textView.textColor = AppTextColor;
    if ([textView.text isEqualToString:@"请输入内容"]) {
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (!(textView.text.length > 0)) {
        textView.textColor = UIColor.lightGrayColor;
        textView.text = @"请输入内容";
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imageArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XOClubPublishImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XOClubPublishImageCell" forIndexPath:indexPath];
    cell.publishImage = self.imageArr[indexPath.row];
    if (indexPath.row == 0) {
        [cell.eliminateButton setHidden:YES];
    }else {
        [cell.eliminateButton setHidden:NO];
    }
    cell.delegate = self;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
            [self selectImage];
            break;
        default:
            break;
    }
}

- (void) selectImage {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action =[UIAlertAction actionWithTitle:@"手机拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showCamera];
    } ];

    [alert addAction:action];
    action = [UIAlertAction actionWithTitle:@"选择相片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showAlbumPhotos];
    }];

    [alert addAction:action];
    action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];

    [self presentViewController:alert animated:YES completion:nil];
}

- (void)clubPublish:(XOClubPublishImageCell *)cell deleteImage:(UIImage *)image {
    ;
    [self.imageArr removeObject:image];
    [self.collectionView deleteItemsAtIndexPaths:@[[self.collectionView indexPathForCell:cell]]];
}

- (void)showCamera {

}

- (void)showAlbumPhotos {

}

    //MARK: - 压缩图片
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize {
        //先判断当前质量是否满足要求，不满足再进行压缩
    __block NSData *finallImageData = UIImagePNGRepresentation(source_image);
    NSUInteger sizeOrigin   = finallImageData.length;
    NSUInteger sizeOriginKB = sizeOrigin / 1024;


    if (sizeOriginKB <= maxSize) {
//        return finallImageData;
        return finallImageData;
    }

        //先调整分辨率
    CGSize defaultSize = CGSizeMake(ScreenWidth * UIScreen.mainScreen.scale, ScreenHeight * UIScreen.mainScreen.scale);
    UIImage *newImage = [self newSizeImage:defaultSize image:source_image];

    finallImageData = UIImagePNGRepresentation(source_image);

        //保存压缩系数
    NSMutableArray *compressionQualityArr = [NSMutableArray array];
    CGFloat avg   = 1.0/250;
    CGFloat value = avg;
    for (int i = 250; i >= 1; i--) {
        value = i*avg;
        [compressionQualityArr addObject:@(value)];
    }

    /*
     调整大小
     说明：压缩系数数组compressionQualityArr是从大到小存储。
     */
        //思路：使用二分法搜索
    finallImageData = [self halfFuntion:compressionQualityArr image:newImage sourceData:finallImageData maxSize:maxSize];
        //如果还是未能压缩到指定大小，则进行降分辨率
    while (finallImageData.length == 0) {
            //每次降100分辨率
        if (defaultSize.width-100 <= 0 || defaultSize.height-100 <= 0) {
            break;
        }
        defaultSize = CGSizeMake(defaultSize.width-100, defaultSize.height-100);
        UIImage *image = [self newSizeImage:defaultSize
                                      image:[UIImage imageWithData:UIImageJPEGRepresentation(newImage,[[compressionQualityArr lastObject] floatValue])]];
        finallImageData = [self halfFuntion:compressionQualityArr image:image sourceData:UIImageJPEGRepresentation(image,1.0) maxSize:maxSize];
        newImage = [UIImage imageWithData:finallImageData];
    }
    return finallImageData;
}

#pragma mark 调整图片分辨率/尺寸（等比例缩放）
- (UIImage *)newSizeImage:(CGSize)size image:(UIImage *)source_image {
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);

    CGFloat tempHeight = newSize.height / size.height;
    CGFloat tempWidth = newSize.width / size.width;

    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }

    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark 二分法
- (NSData *)halfFuntion:(NSArray *)arr image:(UIImage *)image sourceData:(NSData *)finallImageData maxSize:(NSInteger)maxSize {
    NSData *tempData = [NSData data];
    NSUInteger start = 0;
    NSUInteger end = arr.count - 1;
    NSUInteger index = 0;

    NSUInteger difference = NSIntegerMax;
    while(start <= end) {
        index = start + (end - start)/2;

        finallImageData = UIImageJPEGRepresentation(image,[arr[index] floatValue]);

        NSUInteger sizeOrigin = finallImageData.length;
        NSUInteger sizeOriginKB = sizeOrigin / 1024;
        NSLog(@"当前降到的质量：%ld", (unsigned long)sizeOriginKB);
        NSLog(@"\nstart：%zd\nend：%zd\nindex：%zd\n压缩系数：%lf", start, end, (unsigned long)index, [arr[index] floatValue]);

        if (sizeOriginKB > maxSize) {
            start = index + 1;
        } else if (sizeOriginKB < maxSize) {
            if (maxSize-sizeOriginKB < difference) {
                difference = maxSize-sizeOriginKB;
                tempData = finallImageData;
            }
            if (index<=0) {
                break;
            }
            end = index - 1;
        } else {
            break;
        }
    }
    return tempData;
}
@end
